<template>
  <el-container>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="2" id="describe"> 按月查询</el-col>
        <el-col :span="4">
          <div class="block">
            <el-date-picker
              v-model="searchList.yearMonth"
              type="month"
              placeholder="选择月"
            >
            </el-date-picker>
          </div>
        </el-col>
        <el-col :span="4">
          <!-- <el-button type="primary" @click="searchByYearMonth">搜索</el-button> -->
          <el-button @click="reset">重置</el-button></el-col
        >
      </el-row>
      <el-row>
        <el-button type="primary" @click="exportExcelSelection"
          >导出选中数据为excel</el-button
        ><el-button type="primary" @click="exportExcelAll"
          >导出全部数据为excel</el-button
        >
      </el-row>

      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <!-- <el-table-column prop="id" label="编号" width="120"> </el-table-column> -->
        <el-table-column prop="employeeName" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="yearMonth" label="月份" width="120">
        </el-table-column>
        <el-table-column
          prop="monthCheck"
          label="月签到记录"
          width="120"
          :formatter="monthCheckFormatter"
        >
        </el-table-column>
        <el-table-column prop="deduction" label="少勤扣除" width="120">
        </el-table-column>
        <el-table-column prop="award" label="全勤奖" width="120">
        </el-table-column>
        <el-table-column prop="totalSalary" label="实际工资"> </el-table-column>
      </el-table>

      <!-- 不可见表格用来存放要导出的数据 -->
      <!-- 1.当月全部信息表 -->
      <el-table
        id="AllTable"
        ref="multipleTable"
        :data="allData"
        tooltip-effect="dark"
        style="width: 100%; display: none"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <!-- <el-table-column prop="id" label="编号" width="120"> </el-table-column> -->
        <el-table-column prop="employeeName" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="yearMonth" label="月份" width="120">
        </el-table-column>
        <el-table-column
          prop="monthCheck"
          label="月签到记录"
          width="120"
          :formatter="monthCheckFormatter"
        >
        </el-table-column>
        <el-table-column prop="deduction" label="少勤扣除" width="120">
        </el-table-column>
        <el-table-column prop="award" label="全勤奖" width="120">
        </el-table-column>
        <el-table-column prop="totalSalary" label="实际工资"> </el-table-column>
      </el-table>

      <!-- 2.选中的信息表 -->
      <el-table
        id="SelectionTable"
        ref="multipleTable"
        :data="selectionData"
        tooltip-effect="dark"
        style="width: 100%; display: none"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <!-- <el-table-column prop="id" label="编号" width="120"> </el-table-column> -->
        <el-table-column prop="employeeName" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="yearMonth" label="月份" width="120">
        </el-table-column>
        <el-table-column
          prop="monthCheck"
          label="月签到记录"
          width="120"
          :formatter="monthCheckFormatter"
        >
        </el-table-column>
        <el-table-column prop="deduction" label="少勤扣除" width="120">
        </el-table-column>
        <el-table-column prop="award" label="全勤奖" width="120">
        </el-table-column>
        <el-table-column prop="totalSalary" label="实际工资"> </el-table-column>
      </el-table>
      <!-- 不可见表结束 -->
      <el-dialog title="修改薪资" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input
              v-model="form.uname"
              autocomplete="off"
              style="width: 220px"
            ></el-input>
          </el-form-item>
          <el-form-item label="基本工资" :label-width="formLabelWidth">
            <el-input
              v-model="form.base"
              autocomplete="off"
              style="width: 220px"
            ></el-input>
          </el-form-item>
          <el-form-item label="加班工资" :label-width="formLabelWidth">
            <el-input
              v-model="form.add"
              autocomplete="off"
              style="width: 220px"
            ></el-input>
          </el-form-item>
          <el-form-item label="缺勤罚款" :label-width="formLabelWidth">
            <el-input
              v-model="form.minus"
              autocomplete="off"
              style="width: 220px"
            ></el-input>
          </el-form-item>
          <el-form-item label="发薪日" :label-width="formLabelWidth">
            <el-input
              v-model="form.date"
              autocomplete="off"
              style="width: 220px"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-main>

    <!-- 页脚分页 -->
    <div class="fenye">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </el-container>
</template>

<script>
//导出表格用到的依赖
import FileSaver from "file-saver";
// import XLSX from "xlsx";  此种导入方式不可用
import * as XLSX from "xlsx";

export default {
  name: "Salary",
  data() {
    return {
      allData: [], //后端返回的总数据
      tableData: [], //当前页的数据
      selectionData: [], //选中的信息
      page: 1, //页脚显示的当前页
      size: 10, //一页多少条数据
      total: 400, //总条目数

      multipleSelection: [], //当前选中的行

      searchList: {
        //搜索条件的
        yearMonth: "",
      },
      dialogFormVisible: false, //弹出的修改表单
      form: {
        name: "",
        base: "",
        add: "",
        minus: "",
        date: "",
      },
      formLabelWidth: "120px", //宽度
    };
  },
  watch: {
    searchList: {
      handler(val) {
        // console.log(val.yearMonth);
        this.searchByYearMonth(val.yearMonth);
        // console.log(newval);
      },
      deep: true,
      // immediate: true,
    },
  },
  methods: {
    //分页表格数据
    getTableData() {
      //allData为全部数据
      this.tableData = this.allData.slice(
        (this.page - 1) * this.size,
        this.page * this.size
      );
      this.total = this.allData.length; //总条目等于allDaTa长度
    },
    //size改变时的回调，参数为当前的size
    handleSizeChange(val) {
      // console.log("改变每页多少条，当前一页多少条", val);
      this.size = val;
      this.page = 1; //size改变时要把page重置为1，再把参数赋值给size，因为size改变会导致page数量改变
      this.getTableData();
    },
    //page改变时的回调函数，参数为当前页码
    handleCurrentChange(val) {
      // console.log("翻页，当前为第几页", val);
      this.page = val;
      this.getTableData();
    },
    reset() {
      this.getTableData();
      this.getAllSalary();
    },
    //请求所有的薪资信息
    getAllSalary() {
      this.$request.get("salary/queryAllAndName").then((res) => {
        // console.log(res);
        if (res.data.obj != null) {
          // console.log(res.data.obj);
          this.allData = res.data.obj;
          // console.log(this.allData);
          this.getTableData(); //获取信息后更新表单数据
        } else {
          this.$message.error("信息获取失败");
        }
      });
    },
    //按月份搜索
    searchByYearMonth(yearMonth) {
      // console.log(this.searchList.yearMonth);
      const date = new Date(yearMonth);
      const yearMonth1 = this.formatDate(date);
      console.log(yearMonth1);
      this.$request
        .post("salary/queryAllAndNameByMonth", {
          yearMonth: yearMonth1,
        })
        .then((res) => {
          if (res.data.obj != null) {
            this.allData = res.data.obj;
            this.getTableData(); //获取信息后更新表单数据
          } else {
            this.$message.error("信息获取失败");
          }
        });
    },
    // 格式化薪资月份
    yearMouthFormatter(row, column) {
      let date = new Date(row.yearMouth);
      let dateF = this.formatDate(date);
      return dateF;
    },
    formatDate(current_datetime) {
      let formatted_date = "";
      if (current_datetime.getMonth() < 10) {
        formatted_date =
          current_datetime.getFullYear() +
          "-" +
          "0" +
          (current_datetime.getMonth() + 1);
      } else {
        formatted_date =
          current_datetime.getFullYear() +
          "-" +
          (current_datetime.getMonth() + 1);
      }
      return formatted_date;
    },
    //格式化月签到记录
    monthCheckFormatter(row) {
      let monthCheck = row.monthCheck;
      if (monthCheck < 1) {
        return "全勤";
      } else {
        return `缺勤${monthCheck}天`;
      }
    },

    //导出为选中的
    exportExcelSelection() {
      // this.pageNum = 1
      // this.pageSize = 20
      this.$nextTick(function () {
        /* generate workbook object from table */
        var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
        var wb = XLSX.utils.table_to_book(
          document.querySelector("#SelectionTable"),
          xlsxParam
        );
        /* get binary string as output */
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array",
        });
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            "选择导出的薪资信息.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") {
            console.log(e, wbout);
          }
        }
        // this.pageNum = 1
        return wbout;
      });
    },
    //导出当月
    exportExcelAll() {
      // this.pageNum = 1
      // this.pageSize = 20
      this.$nextTick(function () {
        /* generate workbook object from table */
        var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
        var wb = XLSX.utils.table_to_book(
          document.querySelector("#AllTable"),
          xlsxParam
        );
        /* get binary string as output */
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array",
        });
        try {
          FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            "当月薪资表.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") {
            console.log(e, wbout);
          }
        }
        // this.pageNum = 1
        return wbout;
      });
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
      this.selectionData = val;
      console.log(this.selectionData);
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible = true;
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
  },
  mounted() {
    this.getTableData();
    this.getAllSalary();
  },
};
</script>

<style scoped>
.el-header {
  background-color: rgb(42, 53, 66);
  color: #fff;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
.el-row {
  margin-bottom: 10px;
}
#describe {
  height: 40px;
  /* text-align: center; */
  line-height: 40px;
  /* padding: auto; */
  color: #333;
}
.el-col {
  /* background-color: #fff; */
  color: #fff;
}
i {
  font-size: 18px;
}
.fenye {
  position: fixed;
  bottom: 10px;
}
</style>